<?php
namespace Home\Model;
use  Think\Model;
class GoodsModel extends Model{

 /**
     * 获得商品的详细信息
     *
     * @access  public
     * @param   integer     $goods_id
     * @return  void
     */
    function get_goods_info($goods_id,$session='') {

        $DB_PREFIX=C('DB_PREFIX');
        $time = gmtime();
        $sql = 'SELECT g.*, c.measure_unit, b.brand_id, b.brand_name AS goods_brand, m.type_money AS bonus_money, ' .
                // 'IFNULL(AVG(r.comment_rank), 0) AS comment_rank, ' .
                "IFNULL(mp.user_price, g.shop_price * '$session[discount]') AS rank_price,xl.sales_volume " .
                'FROM ' .$DB_PREFIX. 'goods AS g ' .
                'LEFT JOIN ' . $DB_PREFIX . 'category AS c ON g.cat_id = c.cat_id ' .
                'LEFT JOIN ' . $DB_PREFIX . 'brand AS b ON g.brand_id = b.brand_id ' .
                ' LEFT JOIN '. $DB_PREFIX .'touch_goods AS xl ON g.goods_id=xl.goods_id '.
                // 'LEFT JOIN ' . $DB_PREFIX . 'comment AS r ' .
                // 'ON r.id_value = g.goods_id AND comment_type = 0 AND r.parent_id = 0 AND r.status = 1 ' .
                'LEFT JOIN ' . $DB_PREFIX . 'bonus_type AS m ' .
                "ON g.bonus_type_id = m.type_id AND m.send_start_date <= '$time' AND m.send_end_date >= '$time'" .
                " LEFT JOIN " . $DB_PREFIX. "member_price AS mp " .
                "ON mp.goods_id = g.goods_id AND mp.user_rank = '$session[user_rank]' " .
                "WHERE g.goods_id = '$goods_id' AND g.is_delete = 0 " .
                "GROUP BY g.goods_id";
        $list = M()->query($sql);
        $row=$list[0];


        $new_row=array();
        if ($row !== false) {
            /* 用户评论级别取整 */
            // $row['comment_rank'] = ceil($row['comment_rank']) == 0 ? 5 : ceil($row['comment_rank']);




           $new_row['id']=$row['goods_id'];
           $new_row['name']=$row['goods_name'];
           $new_row['goods_number']=$row['goods_number'];
           $new_row['goods_weight']=$row['goods_weight'];
           $new_row['market_price']=price_format($row['market_price']);
           $new_row['market_price_org']=$row['market_price'];
           $new_row['shop_price']=price_format($row['shop_price']);
             /* 修正促销价格 */
            if ($row['promote_price'] > 0) {
                 $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);

                 $new_row['promote_price']= $promote_price > 0 ? price_format($promote_price): '';
                 $new_row['promote_end_date'] = local_date(1,$row['promote_end_date']);
            } else {
                $promote_price='';
                $new_row['promote_price'] = '';
                $new_row['promote_end_date'] = '';
            }

           $new_row['rank_price']=price_format($row['rank_price']);

           $new_row['goods_brand']=$row['goods_brand']?$row['goods_brand']:'';
           // $new_row['goods_desc']=$row['goods_desc'];//商品详情
           $new_row['goods_brief']=$row['goods_brief'];//商品介绍

            /* 修正优惠券 */
            $new_row['bonus_money'] = ($row['bonus_money'] == 0) ? 0 : price_format($row['bonus_money'], false);

            /* 修正商品图片 */
            $new_row['goods_img'] = get_image_path($row['goods_img']);
            /* 商品详情*/
             $new_row['goods_txt_desc']=$row['goods_txt_desc']?$row['goods_txt_desc']:'';
             $new_row['goods_img_desc']=get_image_path($row['goods_img_desc']);
             $new_row['goods_desc_size']=0;
             if($new_row['goods_img_desc'])
             {
                $piczise=getimagesize($new_row['goods_img_desc']);
                $new_row['goods_desc_size']=round($piczise[0]/$piczise[1],2);
             }

            //真实使用的商品价格--优先级关系--促销价--会员价--销售价--市场价
            $new_row['goods_price']=$row['market_price'];
            if($promote_price)
            {
               $new_row['goods_price']=$promote_price;
            }
            else if($row['rank_price'])
            {
              $new_row['goods_price']=$row['rank_price'];
            }
            else if($row['shop_price'])
            {
              $new_row['goods_price']=$row['shop_price'];
            }
            $new_row['format_goods_price']=price_format($new_row['goods_price']);

            $new_row['is_shipping']=$row['is_shipping'];//1指免运费


            //购物车用到
             $new_row['extension_code']=$row['extension_code'];
             $new_row['is_real']=$row['is_real'];
             $new_row['cat_id']=$row['cat_id'];
             $new_row['goods_sn']=$row['goods_sn'];
            

             $row['sales_volume'] = $row['sales_volume']?$row['sales_volume']:0;//销量
             if(empty($row['sales_volume']))//销量统计增加
             {
                // $nCount=0;
                $nCount =M("touch_goods")->where('goods_id = "' . $row['goods_id'] . '"')->count();

                if($nCount<1)
                {
                   M()->execute("INSERT INTO " . $DB_PREFIX . "touch_goods (`goods_id` ,`sales_volume` ) VALUES ( '" . $row['goods_id'] . "' , '0')");
                }
                 
             }
             $new_row['sales_volume'] = $row['sales_volume_base']+$row['sales_volume'];


            /* 处理商品水印图片 */
            // $watermark_img = '';

            // if ($promote_price != 0) {
            //     $watermark_img = "watermark_promote";
            // } elseif ($row['is_new'] != 0) {
            //     $watermark_img = "watermark_new";
            // } elseif ($row['is_best'] != 0) {
            //     $watermark_img = "watermark_best";
            // } elseif ($row['is_hot'] != 0) {
            //     $watermark_img = 'watermark_hot';
            // }

            // if ($watermark_img != '') {
            //     $row['watermark_img'] = $watermark_img;
            // }




            /* 修正重量显示 */
            // $row['goods_weight'] = (intval($row['goods_weight']) > 0) ?
            //         $row['goods_weight'] . L('kilogram') :
            //         ($row['goods_weight'] * 1000) . L('gram');

            /* 修正上架时间显示 */
            // $row['add_time'] = local_date(1, $row['add_time']);


            /* 修正积分：转换为可使用多少积分（原来是可以使用多少钱的积分） */
            // $row['integral'] = $row['integral'] ? round($row['integral'] * 100 / C('integral_scale')) : 0;



            return $new_row;
        } else {
            return false;
        }
    }
      /**
     * 获得商品的属性和规格
     *
     * @access  public
     * @param   integer $goods_id
     * @return  array
     */
   public function get_goods_properties($goods_id) {

       $DB_PREFIX=C('DB_PREFIX');
        /* 对属性进行重新排序和分组 */
        $sql = "SELECT attr_group " .
                "FROM " . $DB_PREFIX . "goods_type AS gt, " . $DB_PREFIX . "goods AS g " .
                "WHERE g.goods_id='$goods_id' AND gt.cat_id=g.goods_type";
        $list = M()->query($sql);
        $result=$list[0];

        $grp = $result['attr_group'];
        if (!empty($grp)) {
            $groups = explode("\n", strtr($grp, "\r", ''));
        }

        /* 获得商品的规格 */
        $sql = "SELECT a.attr_id, a.attr_name, a.attr_group, a.is_linked, a.attr_type, " .
                "g.goods_attr_id, g.attr_value, g.attr_price " .
                'FROM ' . $DB_PREFIX . 'goods_attr AS g ' .
                'LEFT JOIN ' . $DB_PREFIX . 'attribute AS a ON a.attr_id = g.attr_id ' .
                "WHERE g.goods_id = '$goods_id' " .
                'ORDER BY a.sort_order, g.attr_price desc,g.goods_attr_id';
        $res = M()->query($sql);

        $arr['pro'] = array();     // 属性
        $arr['spe'] = array();     // 规格
        $arr['lnk'] = array();     // 关联的属性

        foreach ($res AS $row) {
            $row['attr_value'] = str_replace("\n", '<br />', $row['attr_value']);

            $row['attr_price']=$row['attr_price']?$row['attr_price']:0;

            if ($row['attr_type'] == 0) {
                // $group = (isset($groups[$row['attr_group']])) ? $groups[$row['attr_group']] : '规格';
                // $arr['pro'][$group][$row['attr_id']]['name'] = $row['attr_name'];
                // $arr['pro'][$group][$row['attr_id']]['value'] = $row['attr_value'];
                $arr['spe'][$row['attr_id']]['attr_type'] = 5;
                $arr['spe'][$row['attr_id']]['name'] = $row['attr_name'];
                $arr['spe'][$row['attr_id']]['values'][] = array(
                    'label' => $row['attr_value'],
                    'price' => $row['attr_price'],
                    'format_price' => price_format(abs($row['attr_price']), false),
                    'attr_id' => $row['goods_attr_id']);

            } else {
                $arr['spe'][$row['attr_id']]['attr_type'] = $row['attr_type'];
                $arr['spe'][$row['attr_id']]['name'] = $row['attr_name'];
                $arr['spe'][$row['attr_id']]['values'][] = array(
                    'label' => $row['attr_value'],
                    'price' => $row['attr_price'],
                    'format_price' => price_format(abs($row['attr_price']), false),
                    'attr_id' => $row['goods_attr_id']);
            }

            if ($row['is_linked'] == 1) {
                /* 如果该属性需要关联，先保存下来 */
                $arr['lnk'][$row['attr_id']]['name'] = $row['attr_name'];
                $arr['lnk'][$row['attr_id']]['value'] = $row['attr_value'];
            }
        }

        if(empty($res))
        {
            $em_data['attr_type']="5";
            $em_data['name']="规格";
            $em_data['values'][0]=array("label"=>"如图","price"=>"0","format_price"=>"￥0.00","attr_id"=>"0");
            $arr['spe'][0]=$em_data;
        }

        return $arr;
    }



   /**
     * 获得指定的规格的价格
     *
     * @access  public
     * @param   mix     $spec   规格ID的数组或者逗号分隔的字符串
     * @return  void
     */
  public  function spec_price($spec) {
        if (!empty($spec)) {
            if (is_array($spec)) {
                foreach ($spec as $key => $val) {
                    $spec[$key] = addslashes($val);
                }
            } else {
                $spec = addslashes($spec);
            }

            $where = db_create_in($spec, 'goods_attr_id');

            $sql = 'SELECT SUM(attr_price) AS attr_price FROM ' . C('DB_PREFIX') . "goods_attr WHERE $where";
            $res = M()->query($sql);
            $price = floatval($res[0]['attr_price']);
        } else {
            $price = 0;
        }
        return $price;
    }
  
  /**
     * 计算属性的最低价格之和
     *
     * @access  public
     * @param   integer $goods_id
     * @return  array
     */
    function msum_properties_price($goods_id) {
              /* 获得商品的规格 */
        $sql = "SELECT  g.attr_id, g.attr_value, g.attr_price " .
                'FROM ' . C('DB_PREFIX') . 'goods_attr AS g ' .
                'LEFT JOIN ' . C('DB_PREFIX') . 'attribute AS a ON a.attr_id = g.attr_id ' .
                "WHERE g.goods_id = '$goods_id' " .
                'ORDER BY g.attr_price ';
        $res = M()->query($sql);

        $min_ar=array();
        $min_pro_price=0;
        foreach ($res as $key => $value) {
            if($min_ar[$value['attr_id']])
            { 
              if($min_ar[$value['attr_id']]>$value['attr_price'])
              {
                $min_ar[$value['attr_id']]=$value['attr_price'];
              }
            }
            else
            {
                $min_ar[$value['attr_id']]=$value['attr_price'];
            }
            
        }

        if($min_ar)
        $min_pro_price=array_sum(array_values($min_ar));
        

        return $min_pro_price;

    }

	

}
?>
